<template>
	<div class="upload-box">
		<div class="upload-box__btn" v-if="dataValue.length < count">
			<i v-if="loading" class="el-icon-loading"></i>
			<span v-else @click="() => $refs.upload.click()"> 点击上传 </span>
		</div>
		<div class="upload-box__list">
			<div class="file" v-for="(file, index) in dataValue" :key="file.url">
				<div class="file__col" @click="preview(file)">
					<p>
						<span class="filename">{{ file.name }}</span>
					</p>
				</div>
				<div class="file__col">
					<p>
						<el-button
							icon="el-icon-close"
							type="text"
							size="12"
							@click="onDelete(index, file)"
							class="btn"
						></el-button>
					</p>
				</div>
			</div>
		</div>
		<input type="file" ref="upload" hidden @change="onChange" />
	</div>
</template>

<script>
import { uploadFile } from '@/api'

export default {
	props: {
		value: {
			type: Array,
			required: true
		},
		data: {
			// 上传请求时携带
			type: Object,
			default: () => ({})
		},
		count: {
			type: [Number, String],
			default: Infinity
		},
		beforeDelete: {
			type: Function,
			default: () => (v) => v
		},
		beforeUpload: {
			type: Function,
			default: () => (v) => v
		}
	},
	data() {
		return {
			dataValue: [],
			loading: false
		}
	},
	computed: {},
	mounted() {},
	watch: {
		value: {
			handler(val) {
				this.dataValue = val.slice()
			},
			immediate: true
		}
	},
	methods: {
		onChange($event) {
			const file = $event.target.files[0]
			$event.target.value = ''
			const flag = this.beforeUpload?.(file, this.dataValue.slice())
			if (flag === false) return
			const postData = {
				file: file,
				...this.data
			}
			this.loading = true
			uploadFile(postData)
				.then((res) => {
					this.dataValue.push(res)
					this.$emit('input', this.dataValue)
				})
				.finally(() => {
					this.loading = false
				})
		},
		onDelete(index, file) {
			const flag = this.beforeDelete?.(file, this.dataValue.slice())
			if (flag === false) return
			this.dataValue.splice(index, 1)
			this.$emit('input', this.dataValue)
		},
		preview(file) {
			open(file.filePath)
		}
	},
	components: {}
}
</script>

<style lang="scss" scoped="scoped">
.upload-box {
	border: 1px solid #ccc;
	border-radius: 4px;
	padding: 6px 12px 6px;
	display: flex;
	gap: 10px;
	line-height: 20px;
	max-height: 60px;
	&__btn {
		color: #7d9dff;
		font-size: 13px;
		cursor: pointer;
	}
	&__list {
		flex: 1;
		overflow-y: auto;
	}
}

.file {
	font-size: 12px;
	display: grid;
	grid-template-columns: 1fr 12px;
	align-items: center;
	// padding-bottom: 8px;
	&:not(:last-child) {
		padding-bottom: 0;
	}

	&__col {
		position: relative;
		height: 20px;
		font-size: 12px;
		p {
			position: absolute;
			left: 0;
			right: 0;
			top: 0;
			bottom: 0;
			line-height: 20px;
			@include textElli;

			.btn {
				position: absolute;
				left: 50%;
				top: 50%;
				transform: translate(-50%, -50%);
			}

			.filename {
				cursor: pointer;
				color: #444;
			}
		}
	}
}
</style>
